import React, { useState, useEffect, useRef } from "react";
import {
  Descriptions,
  message,
  Modal,
  Button,
  Input,
  List,
  Skeleton,
} from "antd";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import ProForm, {
  ProFormText,
  ProFormDigit,
  ProFormRadio,
  ProFormDependency,
  ProFormTextArea,
} from "@ant-design/pro-form";
import { CheckOutlined } from "@ant-design/icons";
import { getWaitCollectOrderInfoByRasId, recoveryCheck } from "@/api/order";

import { ProCard } from "@ant-design/pro-components";
import UploadFile from "@/components/UploadFile";
import { filterRasCode } from "@/const";
import { history } from "umi";

export default () => {
  const formRef = useRef();
  const [info, setInfo] = useState({});
  const [searchValue, setSearchValue] = useState("");
  const [booksRasCodeList, setBooksRasCodeList] = useState([]);
  const [loading, setLoading] = useState(false);

  const handleAddOrUpdate = async (fields) => {
    const postData = {
      ...fields,
    };
    const res = await recoveryCheck(postData);
    const { success, willSend } = res.data;
    if (success) {
      message.success("收货成功");
      setInfo({});
      formRef.current.resetFields();
    }

    if (willSend) {
      Modal.confirm({
        title: "提示",
        content: "该书包要在15日发出，是否需要跳转到发货页面？",
        onOk: async () => {
          history.push(`/sendGoods?bagCode=${postData.bagCode}`);
        },
      });
    }
  };

  const handleQuery = async (bagCode) => {
    setLoading(true);
    const res = await getWaitCollectOrderInfoByRasId({
      bagCode,
    });
    if (res.data) {
      if (res.data.readServiceStatus != 3) {
        message.error("书包状态非法，不能进行收货");
      }
      setInfo(res.data);
      setBooksRasCodeList(
        res.data?.booksRasCode?.map((item) => {
          return {
            code: item,
            ok: false,
          };
        })
      );
    }
    setLoading(false);
  };
  return (
    <PageContainer>
      <ProCard ghost>
        <ProForm
          labelCol={{
            span: 2,
          }}
          layout="inline"
          formRef={formRef}
          submitter={{
            // 配置按钮文本
            searchConfig: {
              submitText: "确定收货",
            },
            render: (props, dom) =>
              !loading &&
              info.schoolbagRasCode &&
              info?.readServiceStatus == 3 ? (
                <FooterToolbar>{dom[1]}</FooterToolbar>
              ) : null,
          }}
          onFinish={async (values) => {
            return await handleAddOrUpdate(values);
          }}
          initialValues={{
            type: 0,
          }}
        >
          <ProFormText
            width="lg"
            name="bagCode"
            placeholder="扫码/感应芯片关联发货的书包码"
            // onBlur={(e) => {
            //   if (!e.target.value) return;
            //   const bagCode = filterRasCode(e.target.value);
            //   handleQuery(bagCode);
            //   formRef.current.setFieldsValue({
            //     bagCode,
            //   });
            // }}
            rules={[
              { required: true, message: "请扫码/感应芯片关联发货的书包码" },
              {
                max: 50,
                message: "最长为50位",
              },
            ]}
          />
          <ProFormDependency name={["bagCode"]}>
            {({ bagCode }) => {
              return (
                <ProForm.Item>
                  <Button
                    loading={loading}
                    type="primary"
                    onClick={() => {
                      if (!bagCode) return;
                      const bagCodeShot = filterRasCode(bagCode);
                      handleQuery(bagCodeShot);
                      formRef.current.setFieldsValue({
                        bagCode: bagCodeShot,
                      });
                    }}
                  >
                    查询
                  </Button>
                </ProForm.Item>
              );
            }}
          </ProFormDependency>

          {info.schoolbagCode && (
            <>
              <ProCard title="书包信息" style={{ marginTop: 20 }}>
                <Descriptions>
                  <Descriptions.Item label="书包芯片码">
                    {info.schoolbagRasCode}
                  </Descriptions.Item>
                  <Descriptions.Item label="组号">
                    {info.groupCode}
                  </Descriptions.Item>
                  <Descriptions.Item label="书本数量">15本</Descriptions.Item>
                  <Descriptions.Item label="书包号">
                    {info.schoolbagCode}
                  </Descriptions.Item>
                  <Descriptions.Item label="期数">
                    第{info.serviceNum}期
                  </Descriptions.Item>
                </Descriptions>
              </ProCard>
              <ProCard style={{ marginTop: 20 }} title="订单信息">
                <Descriptions>
                  <Descriptions.Item label="书包名称">
                    {info.schoolbagName}
                  </Descriptions.Item>
                  <Descriptions.Item label="姓名电话">
                    {info.username}-{info.mobile}
                  </Descriptions.Item>
                  <Descriptions.Item label="用户地址">
                    {info.province}
                    {info.city}
                    {info.area}
                    {info.detail}
                  </Descriptions.Item>
                </Descriptions>
              </ProCard>
              {info?.readServiceStatus == 3 ? (
                <>
                  <ProCard title="核对书籍码" style={{ marginTop: 20 }}>
                    <List
                      style={{ width: 400 }}
                      itemLayout="horizontal"
                      dataSource={booksRasCodeList}
                      renderItem={(item) => (
                        <List.Item>
                          <Skeleton title={false} loading={false} active>
                            <List.Item.Meta title={item.code} />
                            {item.ok && (
                              <CheckOutlined style={{ color: "#00d886" }} />
                            )}
                          </Skeleton>
                        </List.Item>
                      )}
                    />

                    <Input.Search
                      value={searchValue}
                      placeholder="扫码/感应芯片关联发货的书籍"
                      style={{ width: 400 }}
                      enterButton="核对"
                      onChange={(e) => {
                        setSearchValue(e.target.value);
                      }}
                      onSearch={(val) => {
                        const bagCode = filterRasCode(val);
                        const idx = booksRasCodeList.findIndex(
                          (item) => item.code == bagCode
                        );
                        if (idx >= 0) {
                          const arr = [...booksRasCodeList];
                          arr[idx].ok = true;
                          setBooksRasCodeList(arr);
                          setSearchValue("");
                        } else {
                          message.warning("书籍码不匹配");
                        }
                      }}
                    />
                  </ProCard>

                  <ProCard style={{ marginTop: 20 }} title="核对">
                    <div style={{ marginBottom: 20 }}>
                      <ProFormRadio.Group
                        label="书包状况"
                        name="type"
                        options={[
                          {
                            value: 0,
                            label: "书本完整",
                          },
                          {
                            value: 1,
                            label: "书本损坏",
                          },
                        ]}
                      />
                    </div>

                    <ProFormDependency name={["type"]}>
                      {({ type }) => {
                        return (
                          type === 1 && (
                            <>
                              <ProFormTextArea
                                wrapperCol={{
                                  span: 12,
                                }}
                                fieldProps={{
                                  rows: 5,
                                  maxLength: 2000,
                                  showCount: true,
                                }}
                                name="deductionReason"
                                label="损坏说明"
                                placeholder="请输入损坏说明"
                                rules={[
                                  { required: true, message: "请输入损坏说明" },
                                ]}
                              />
                              <ProForm.Item
                                style={{ margin: "20px 0" }}
                                label="上传图片"
                                name="deductionImg"
                                rules={[
                                  { required: true, message: "请上传图片" },
                                ]}
                              >
                                <UploadFile maxCount={1} />
                              </ProForm.Item>

                              <ProFormDigit
                                label="押金扣除"
                                name="deductionDeposit"
                                placeholder="请输入"
                                addonAfter="元"
                                fieldProps={{
                                  precision: 2,
                                }}
                                rules={[{ required: true, message: "请输入" }]}
                              />
                            </>
                          )
                        );
                      }}
                    </ProFormDependency>
                  </ProCard>
                </>
              ) : null}
            </>
          )}
        </ProForm>
      </ProCard>
    </PageContainer>
  );
};
